package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.model.UserPushTimeEntity;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.UserService;
import com.lab205.send.producer.SendMQInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by SN on 2017/2/18.
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private ActorRepository actorRepository;
    @Resource
    private AlarmPushRepository alarmPushRepository;
    @Resource
    private UserActorRepository userActorRepository;
    @Resource
    private UserPushTimeRepository userPushTimeRepository;


    @Transactional
    public UserDto loginCheck(String loginName, String loginPwd, String inputCode) throws Exception {
        UserDto userDto = userRepository.loginCheck(loginName, loginPwd);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteAddr();
        HttpSession rdsUserLoginSession = request.getSession();

        String requestDevice = request.getParameter("requestDevice");
        if (null == requestDevice || "" == requestDevice)
            if (!rdsUserLoginSession.getAttribute("imageCode").equals(inputCode.toUpperCase()))
                userDto.setLoginResult(5);

        // 登录成功后设置Session属性用于验证
        if (userDto.getLoginResult() == 2) {
            rdsUserLoginSession.setAttribute("rdsUserLoginSession", userDto);
            userRepository.updateIP(loginName, ip);
        } else {
            UserDto userDto1 = new UserDto();
            userDto1.setLoginResult(userDto.getLoginResult());
            userDto = userDto1;
        }

        return userDto;
    }

    public UserDto getUserById(Integer userId) throws Exception {
        return userRepository.getUserById(userId);
    }

    @Transactional
    public Integer updateUserById(UserDto userDto) throws Exception {
        return userRepository.updateUserById(userDto.getUserName(), userDto.getUserSex(), userDto.getUserMobile(), userDto.getUserEmail(), userDto.getUserIcon(), userDto.getUserRemarks(), userDto.getUserId());
    }

    @Transactional
    public Integer updatePwdById(String oldPwd, String newPwd, Integer userId) throws Exception {
        String loginPwd = userRepository.getPwdById(userId);
        if (oldPwd.equals(loginPwd)) {
            return userRepository.updatePwdById(newPwd, userId);
        }
        return 0;
    }

    public Integer sendMQ(String phone, String code, String userName) throws Exception {
        System.out.println(phone + "," + code + "," + userName);
        SendMQInfo.sendSMSInfo("NBSN", phone, "宁波少年",
                "SMS_15150057", "{\"code\":\"" + code + "\",\"product\":\"" + userName + "\"}");
        return 1;
    }

    public List<UserDto> getUser4addNotice() throws Exception {
        return userRepository.getUser4addNotice();
    }

    /**
     * @Description: 根据登录名获取验证码
     * @Author feng
     * @Date 2017/3/10 11:30
     */
    @Transactional
    public String getVerificationCodeByLoginName(String loginName) throws Exception {

        if (loginName == null || "".equals(loginName)) {
            return "登录账号不能为空";
        }

        String phone = userRepository.getPhoneByLoginName(loginName);

        if (phone == null || "".equals(phone)) {
            return "手机号不存在";
        }

        String userName = userRepository.getUserNameByLoginName(loginName);

        if (userName == null || "".equals(userName)) {
            return "用户名不存在";
        }

        String code = String.valueOf(1 + (int) (Math.random() * ((999999 - 1) + 1)));

        userRepository.updateUserRemakersByLoginName(loginName, code);

        SendMQInfo.sendSMSInfo("NBSN", phone, "宁波少年",
                "SMS_15150057", "{\"code\":\"" + code + "\",\"product\":\"" + userName + "\"}");

        return "发送验证码成功";
    }

    /**
     * @param loginName
     * @param verificationCode
     * @Description: 检验验证码
     * @Author feng
     * @Date 2017/3/10 18:25
     */
    public String checkVerificationCodeByLoginName(String loginName, int verificationCode) throws Exception {

        if (loginName == null || "".equals(loginName)) {
            return "登录账号不能为空";
        }

        String userRemakers = userRepository.getUserRemakersByLoginName(loginName);

        if (userRemakers == null || "".equals(userRemakers)) {
            return "系统错误";
        }

        if (!userRemakers.equals(String.valueOf(verificationCode))) {
            return "输入的验证码错误";
        }

        return "验证码验证成功";
    }

    /**
     * @param newPwd
     * @param loginName
     * @Description: 根据登录名重置密码
     * @Author feng
     * @Date 2017/3/11 11:44
     */
    @Transactional
    public String updatePwdByLoginName(String newPwd, String loginName) throws Exception {

        if (newPwd == null || "".equals(newPwd)) {
            return "新密码不能为空";
        }

        String loginPwd = userRepository.getPwdByLoginName(loginName);

        if (newPwd.equals(loginPwd)) {
            return "新密码与旧密码相同";
        }

        Integer result = userRepository.updatePwdByLoginName(newPwd, loginName);

        if (result == 0) {
            return "重置密码失败";
        }

        return "重置密码成功";
    }

    public String getActorNameByUserId(Integer userId) throws Exception {
        String result = "";
        List<String> mLists = userRepository.getActorNameByUserId(userId);
        if (mLists == null || mLists.size() == 0) {
            return result;
        }
        result = mLists.get(0);
        for (int i = 1; i < mLists.size(); i++) {
            result += "/";
            result += mLists.get(i);
        }
        return result;
    }


    @Transactional
    public Integer updateUserById4app(Integer userId, String userIcon, String userName, String userSex, String userEmail) throws Exception {
        return userRepository.updateUserById4app(userId, userIcon, userName, userSex, userEmail);
    }

    public DTResponseDto getUser4DT(DTRequestDto dtRequestDto, Integer orgId, Integer actorId) throws Exception {
        List<UserDto> dto4DTs = userRepository.getUser4DT(dtRequestDto, orgId, actorId);
        Integer count = userRepository.getCount4DT(orgId, dtRequestDto.getSearch(), actorId);
        List<ActorDto> actorDtos = userRepository.getActorNames4User();
        for (UserDto userDto : dto4DTs) {
            for (ActorDto actorDto : actorDtos) {
                if (userDto.getUserId() == actorDto.getUserId()) {
                    userDto.setUserActors(actorDto.getActorName());
                    break;
                }
            }
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    @Transactional
    public Integer deactivateUserById(String userIds, Integer userState) throws Exception {
        String[] userIdArray = userIds.split(",");
        int i = 0;
        if (userState == 0) {
            for (i = 0; i < userIdArray.length; i++) {
                userRepository.deactivateUserById(Integer.parseInt(userIdArray[i]));
            }
        } else {
            for (i = 0; i < userIdArray.length; i++) {
                userRepository.activateUserById(Integer.parseInt(userIdArray[i]));
            }
        }
        return i;
    }

    @Transactional
    public Integer addUser(UserDto userDto) throws Exception {
        Integer userId = userRepository.save(userDto.toBean()).getUserId();
        UserPushTimeDto pushTimeDto = new UserPushTimeDto(userId, "0", "0", "0", "0", "0", "0", "0", "0", "0");
        userPushTimeRepository.save(pushTimeDto.toBean());
        if (userDto.getUserActors().equals("") || userDto.getUserActors().equals("noActor")) {
        } else {
            String[] userActorIds = userDto.getUserActors().split(",");
            for (String userActorid : userActorIds) {
                UserActorDto userActorDto = new UserActorDto(Integer.parseInt(userActorid), userId);
                userActorRepository.save(userActorDto.toBean()).getAuId();
            }
        }
        return userId;
    }

    @Transactional
    public Integer updateUserByUserId(UserDto userDto) throws Exception {
        if (userDto.getUserActors() == null) {
        } else {
            userActorRepository.deleteUserActorByUserId(userDto.getUserId());
            if (!userDto.getUserActors().equals("noActor")) {
                String[] userActorIds = userDto.getUserActors().split(",");
                for (String userActorId : userActorIds) {
                    UserActorDto userActorDto = new UserActorDto(Integer.parseInt(userActorId), userDto.getUserId());
                    userActorRepository.save(userActorDto.toBean()).getAuId();
                }
            }
        }
        return userRepository.updateUserByUserId(userDto.getUserName(), userDto.getUserMobile(), userDto.getUserSex(),
                userDto.getUserEmail(), userDto.getUserState(), userDto.getUserRemarks(), userDto.getUserId(), userDto.getOrgId());
    }

    public Integer getCountByLoginName(String loginName) throws Exception {
        return userRepository.getCountByLoginName(loginName);
    }

    public List<ActorDto> getActor4Select() throws Exception {
        return actorRepository.getActor4Select();
    }

    @Transactional
    public Integer deleteUserById(Integer userId) throws Exception {
        userActorRepository.deleteUserActorByUserId(userId);
        return userRepository.deleteUserById(userId);
    }

    @Transactional
    public Integer resetPswByUserId(Integer userId) throws Exception {
        return userRepository.resetPswByUserId(userId);
    }

    @Override
    public UserPushTimeEntity getPushTimeByUserId(Integer userId) {
        return userPushTimeRepository.getPushTimeByUserId(userId);
    }

    @Override
    @Transactional
    public UserPushTimeEntity updatePushTimeByUserId(UserPushTimeDto userPushTimeDto) throws Exception {
        return userPushTimeRepository.save(userPushTimeDto.toBean());
    }

    @Override
    public List<CornerDto> getConner4App(Integer orgId,Integer userId) throws Exception {
        /*设备类型  1:标牌; 2:信号灯; 3:信号机; 4:太阳能产品; 5:限高杆; 6:标线; 7:护栏; 8:监控箱; 9:井盖;*/
        UserPushTimeEntity userPushTime = userPushTimeRepository.getPushTimeByUserId(userId);
        List<CornerDto> cornerDtos = new ArrayList<>();
        CornerDto type1 = alarmPushRepository.getCorner4App(orgId, 1, userPushTime.getRoadSignTime());
        type1.setPushType(1);
        type1.setLastTime(userPushTime.getRoadSignTime());
        cornerDtos.add(type1);
        CornerDto type2 = alarmPushRepository.getCorner4App(orgId, 2, userPushTime.getSignalLampTime());
        type2.setPushType(2);
        type2.setLastTime(userPushTime.getSignalLampTime());
        cornerDtos.add(type2);
        CornerDto type3 = alarmPushRepository.getCorner4App(orgId, 3, userPushTime.getSignalMachineTime());
        type3.setPushType(3);
        type3.setLastTime(userPushTime.getSignalMachineTime());
        cornerDtos.add(type3);
        CornerDto type4 = alarmPushRepository.getCorner4App(orgId, 4, userPushTime.getSolarEnergyTime());
        type4.setPushType(4);
        type4.setLastTime(userPushTime.getSolarEnergyTime());
        cornerDtos.add(type4);
        CornerDto type5 = alarmPushRepository.getCorner4App(orgId, 5,  userPushTime.getHighLeverTime());
        type5.setPushType(5);
        type5.setLastTime(userPushTime.getHighLeverTime());
        cornerDtos.add(type5);
        CornerDto type6 = alarmPushRepository.getCorner4App(orgId, 6, userPushTime.getRoadLineTime());
        type6.setPushType(6);
        type6.setLastTime(userPushTime.getRoadLineTime());
        cornerDtos.add(type6);
        CornerDto type7 = alarmPushRepository.getCorner4App(orgId, 7, userPushTime.getGuardrailTime());
        type7.setPushType(7);
        type7.setLastTime(userPushTime.getGuardrailTime());
        cornerDtos.add(type7);
        CornerDto type8 = alarmPushRepository.getCorner4App(orgId, 8, userPushTime.getMonitorTime());
        type8.setPushType(8);
        type8.setLastTime(userPushTime.getMonitorTime());
        cornerDtos.add(type8);
        CornerDto type9 = alarmPushRepository.getCorner4App(orgId, 9,  userPushTime.getCoverTime());
        type9.setPushType(9);
        type9.setLastTime(userPushTime.getCoverTime());
        cornerDtos.add(type9);
        return cornerDtos;
    }


    @Override
    @Transactional
    public Integer updatePushTimeByType(Integer userId, Integer type) throws Exception {
        Integer result = 0;
        String nowTime = String.valueOf(System.currentTimeMillis() / 1000);
        switch (type) {
            case 1:
                result = userPushTimeRepository.updateRoadSignTime(userId, nowTime);
                break;
            case 2:
                result = userPushTimeRepository.updateSignalLampTime(userId, nowTime);
                break;
            case 3:
                result = userPushTimeRepository.updateSignalMachineTime(userId, nowTime);
                break;
            case 4:
                result = userPushTimeRepository.updateSolarEnergyTime(userId, nowTime);
                break;
            case 5:
                result = userPushTimeRepository.updateHighLeverTime(userId, nowTime);
                break;
            case 6:
                result = userPushTimeRepository.updateRoadLineTime(userId, nowTime);
                break;
            case 7:
                result = userPushTimeRepository.updateGuardrailTime(userId, nowTime);
                break;
            case 8:
                result = userPushTimeRepository.updateMonitorTime(userId, nowTime);
                break;
            case 9:
                result = userPushTimeRepository.updateCoverTime(userId, nowTime);
                break;
        }
        return result;
    }

    @Override
    public List<AlarmPushDto> getCurrentPushList(Integer orgId, Integer deviceType, Integer userId,String oldTime, Integer mCount, Integer mSize) throws Exception {
        UserPushTimeEntity userPushTime = userPushTimeRepository.getPushTimeByUserId(userId);
        String newTime = "";
        switch (deviceType) {
            case 1:
                newTime = userPushTime.getRoadSignTime();
                break;
            case 2:
                newTime = userPushTime.getSignalLampTime();
                break;
            case 3:
                newTime = userPushTime.getSignalMachineTime();
                break;
            case 4:
                newTime = userPushTime.getSolarEnergyTime();
                break;
            case 5:
                newTime = userPushTime.getHighLeverTime();
                break;
            case 6:
                newTime = userPushTime.getRoadLineTime();
                break;
            case 7:
                newTime = userPushTime.getGuardrailTime();
                break;
            case 8:
                newTime = userPushTime.getMonitorTime();
                break;
            case 9:
                newTime = userPushTime.getCoverTime();
                break;
        }
        return alarmPushRepository.getCurrentPushList(orgId, deviceType,newTime,oldTime, mCount, mSize);
    }


}
